// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dfa.axis.v1_19.matchtables;

import java.util.HashSet;
import java.util.Set;

/**
 * Default implementation of LookupObject that only cares about one column in the DT file.
 * Handles aggregation and expects sub-classes to do actual match table generation.
 *
 * @author Moshe Kahan
 */
abstract class AbstractSimpleLookupObject implements LookupObject {

  private String columnHeader;
  private int columnIndex;

  protected Set<Long> entityIds;

  /**
   * Subclasses pass in column/field name that class should aggregate on.
   * @param columnHeader field name that class will use to perform lookups.
   */
  AbstractSimpleLookupObject(String columnHeader) {
    this.columnHeader = columnHeader;
    this.entityIds = new HashSet<Long>();
    this.columnIndex = -1;
  }

  /**
   * Called when LookupObjectManager is parsing the DT file header. Method stores index
   * of column of interest.
   * @param index in DT file columns
   * @param header name of this DT file field/column
   */
  public void addHeader(int index, String header) throws DataTransferFileException {
    if (columnHeader.equals(header)) {
      columnIndex = index;
    }
  }

  /**
   * Called to clear the DT header information' usually because you're processing a new file.
   */
  public void clearHeaders() {
    columnIndex = -1;
  }

  /**
   * Called after DT file line has been tokenized into array of Strings.  Aggregate
   * over column of interest.
   *
   * @param values array of tokenized Strings of DT file line
   */
  public void addValues(String[] values) throws DataTransferFileException {
    if (columnIndex > -1) {
      String value = values[columnIndex];
      if (value != null && !value.isEmpty() && !value.equals("0")) {
        entityIds.add(Long.valueOf(value));
      }
    }
  }
}
